<template>
  <Page class="bg-[#f5f7fa] min-h-screen">
    <!-- 顶部蓝色渐变背景 -->
    <PageHeader title="申请用户" :showBack="true" :onlyBack="true"/>
    <view
      class="fixed top-0 left-0 w-full z-[3] h-[250rpx] bg-gradient-to-b from-[#2196F3] to-[#6ec6ff] rounded-b-[40rpx]"
    ></view>

    <!-- 吸顶标题栏 -->
    <view class="sticky top-0 z-4 px-[32rpx] pt-[32rpx] pb-[24rpx] bg-transparent">
      <view class="flex items-center justify-end mb-[24rpx]">
        <!-- <view class="flex items-center">
          <nut-button
            size="small"
            type="default"
            class="bg-white/20 text-white border-white/30 mr-[16rpx]"
            @click="handleBack"
          >
            <IconFont name="left" size="20" />
          </nut-button>
          <text class="text-[36rpx] font-bold text-white">申请用户</text>
        </view> -->
        <view class="flex items-center gap-x-[12rpx]">
          <text class="text-[24rpx] text-white/80">共{{ applicants.length }}人</text>
        </view>
      </view>

      <!-- 任务信息卡片 -->
      <view class="bg-white/90 backdrop-blur-sm rounded-[24rpx] p-[24rpx] shadow-lg">
        <view class="flex items-start justify-between mb-[16rpx]">
          <text class="text-[28rpx] font-bold text-[#333] flex-1 mr-[16rpx]">
            {{ taskInfo.title }}
          </text>
          <view
            class="px-[12rpx] py-[4rpx] rounded-[12rpx] text-[20rpx] font-medium"
            :class="taskInfo.statusClass"
          >
            {{ taskInfo.status }}
          </view>
        </view>
        <view class="flex items-center justify-between">
          <text class="text-[24rpx] text-[#666]">{{ taskInfo.amount }}</text>
          <text class="text-[22rpx] text-[#999]">申请截止：{{ taskInfo.deadline }}</text>
        </view>
      </view>
    </view>

    <!-- 申请用户列表 -->
    <view class="pt-[20rpx] pb-[32rpx] px-[32rpx]">
      <view class="flex flex-col gap-y-[20rpx]">
        <!-- 申请用户卡片 -->
        <view
          v-for="(applicant, index) in applicants"
          :key="applicant.id"
          class="bg-white rounded-[24rpx] p-[24rpx] shadow-md"
          @click="goToUserDetail(applicant)"
        >
          <!-- 用户基本信息 -->
          <view class="flex items-start justify-between mb-[20rpx]">
            <view class="flex items-center flex-1">
              <!-- 用户头像 -->
              <image
                :src="applicant.avatar"
                class="w-[80rpx] h-[80rpx] rounded-[40rpx] mr-[16rpx]"
                mode="aspectFill"
              />
              
              <!-- 用户信息 -->
              <view class="flex-1">
                <view class="flex items-center mb-[8rpx]">
                  <text class="text-[28rpx] font-bold text-[#333] mr-[12rpx]">
                    {{ applicant.name }}
                  </text>
                  <!-- 个人/企业标志 -->
                  <view
                    class="px-[8rpx] py-[2rpx] rounded-[8rpx] text-[20rpx] font-medium"
                    :class="applicant.isCompany ? 'bg-yellow-500 text-white' : 'bg-green-500 text-white'"
                  >
                    {{ applicant.isCompany ? '企业' : '个人' }}
                  </view>
                </view>
                
                <!-- 用户标签 -->
                <view class="flex items-center gap-x-[8rpx] mb-[8rpx]">
                  <view
                    v-for="tag in applicant.tags"
                    :key="tag"
                    class="px-[8rpx] py-[2rpx] bg-[#f5f5f5] text-[#666] text-[20rpx] rounded-[6rpx]"
                  >
                    {{ tag }}
                  </view>
                </view>
                
                <!-- 申请时间 -->
                <text class="text-[22rpx] text-[#999]">
                  申请时间：{{ applicant.applyTime }}
                </text>
              </view>
            </view>
          </view>

          <!-- 申请理由 -->
          <view class="mb-[20rpx]">
            <text class="text-[24rpx] text-[#666] leading-[1.6]">
              {{ applicant.reason }}
            </text>
          </view>

          <!-- 操作按钮 -->
          <view class="flex items-center gap-x-[12rpx]">
            <nut-button
              size="small"
              type="default"
              class="flex-1 border-blue-500 text-blue-500 bg-transparent rounded-[20rpx] py-[12rpx] text-[24rpx] font-medium hover:bg-blue-50 transition-all duration-200"
              @click="handleContact(applicant)"
            >
              立即联系
            </nut-button>
            
            <nut-button
              size="small"
              type="primary"
              class="flex-1 bg-green-500 border-none rounded-[20rpx] py-[12rpx] text-[24rpx] font-medium text-white shadow-md hover:shadow-lg transition-all duration-200"
              :disabled="applicant.status === 'accepted' || applicant.status === 'rejected'"
              @click="handleAccept(applicant)"
            >
              {{ applicant.status === 'accepted' ? '已接受' : '接受' }}
            </nut-button>
            
            <nut-button
              size="small"
              type="default"
              class="flex-1 border-red-500 text-red-500 bg-transparent rounded-[20rpx] py-[12rpx] text-[24rpx] font-medium hover:bg-red-50 transition-all duration-200"
              :disabled="applicant.status === 'accepted' || applicant.status === 'rejected'"
              @click="handleReject(applicant)"
            >
              {{ applicant.status === 'rejected' ? '已拒绝' : '拒绝' }}
            </nut-button>
          </view>
          
          <!-- 评价按钮 - 仅对已完成的用户显示 -->
          <view v-if="applicant.status === 'accepted'" class="mt-[12rpx]">
            <nut-button
              size="small"
              type="default"
              class="w-full border-yellow-500 text-yellow-500 bg-transparent rounded-[20rpx] py-[12rpx] text-[24rpx] font-medium hover:bg-yellow-50 transition-all duration-200"
              @click="handleEvaluate(applicant)"
            >
              评价用户
            </nut-button>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view
        v-if="applicants.length === 0"
        class="flex flex-col items-center justify-center py-[120rpx]"
      >
        <image
          src="http://www.dzgktf.com/templets/default/images/wtyt.jpg"
          class="w-[200rpx] h-[200rpx] rounded-[100rpx] mb-[32rpx] opacity-50"
          mode="aspectFill"
        />
        <text class="text-[28rpx] text-[#999] mb-[16rpx]">暂无申请用户</text>
        <text class="text-[24rpx] text-[#ccc]">等待用户申请中...</text>
      </view>
    </view>
    
    <!-- 评价弹窗 -->
    <EvaluateModal
      :visible="evaluateModalVisible"
      :userInfo="currentEvaluateUser"
      @confirm="handleEvaluateConfirm"
      @cancel="handleEvaluateCancel"
    />
  </Page>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { post } from "@/utils/request";
// import { Button as nutButton } from "@nutui/nutui-taro";
import EvaluateModal from "@/components/EvaluateModal.vue";

/**
 * 申请用户管理列表页面
 * 显示申请用户信息，提供联系和接受申请功能
 */

 const statusMap = {
  1: '发布中',
  2: '进行中',
  3: '待确认完成',
  4: '确认没完成',
  5: '确认已完成',
  6: '已评价',
 }

 const buttonMap = {
  1: [],
  2: ['聊天', '接受', '拒绝'],
  3: ['聊天', '验证完成', '有纠纷'],
  4: [],
  5: ['去评价'],
  6: [],
 }

// 任务信息
const taskInfo = ref({
  title: "超市临时导购员（周末2天）",
  status: "执行中",
  statusClass: "bg-[#f6ffed] text-[#52c41a]",
  amount: "￥180/天",
  deadline: "本周日 22:00",
});

// 申请用户列表
const applicants = ref([
  {
    id: "a1",
    name: "张小美",
    avatar: "http://www.dzgktf.com/templets/default/images/wtyt.jpg",
    isCompany: false,
    tags: ["有经验", "热情开朗"],
    applyTime: "今天 10:30",
    reason: "我有2年超市导购经验，熟悉食品区域商品，能够热情接待顾客并介绍促销活动。周末时间充裕，可以保证按时到岗。",
    status: "pending", // pending, accepted, rejected
  },
  {
    id: "a2",
    name: "李强",
    avatar: "http://www.dzgktf.com/templets/default/images/wtyt.jpg",
    isCompany: false,
    tags: ["大学生", "兼职经验"],
    applyTime: "今天 09:15",
    reason: "我是大学生，有多次兼职经验，性格外向善于沟通。对食品销售有一定了解，能够快速上手工作。",
    status: "pending",
  },
  {
    id: "a3",
    name: "王阿姨",
    avatar: "http://www.dzgktf.com/templets/default/images/wtyt.jpg",
    isCompany: false,
    tags: ["本地人", "稳定可靠"],
    applyTime: "昨天 16:45",
    reason: "我是本地人，有丰富的销售经验，熟悉周边环境。工作认真负责，能够长期稳定工作。",
    status: "accepted",
  },
  {
    id: "a4",
    name: "阳光兼职服务",
    avatar: "http://www.dzgktf.com/templets/default/images/wtyt.jpg",
    isCompany: true,
    tags: ["专业团队", "服务保障"],
    applyTime: "昨天 14:20",
    reason: "我们是专业的兼职服务团队，有稳定的兼职人员资源。可以提供2名经验丰富的导购员，保证服务质量。",
    status: "rejected",
  },
  {
    id: "a5",
    name: "陈小华",
    avatar: "http://www.dzgktf.com/templets/default/images/wtyt.jpg",
    isCompany: false,
    tags: ["应届生", "学习能力强"],
    applyTime: "昨天 11:30",
    reason: "我是应届毕业生，虽然没有相关经验，但学习能力强，能够快速适应工作环境。希望获得这次机会。",
    status: "pending",
  },
]);

/**
 * 返回上一页
 */
const handleBack = () => {
  Taro.navigateBack();
};

/**
 * 立即联系用户
 * @param {Object} applicant - 申请用户信息
 */
const handleContact = (applicant) => {
  Taro.navigateTo({
    url: `/pages/message/message?userId=${applicant.id}&userName=${applicant.name}`,
  })
};

// 评价弹窗相关
const evaluateModalVisible = ref(false);
const currentEvaluateUser = ref({});

const handleEvaluate = (applicant) => {
  currentEvaluateUser.value = {
    name: applicant.name,
    avatar: applicant.avatar,
    taskTitle: taskInfo.value.title
  };
  evaluateModalVisible.value = true;
};

/**
 * 评价确认
 */
const handleEvaluateConfirm = (evaluateData) => {
  console.log('评价数据：', evaluateData);
  
  // 显示完整的评价内容
  console.log('评分：', evaluateData.rating);
  console.log('完整评价内容：', evaluateData.comment);
  console.log('选择的标签：', evaluateData.tags);
  console.log('用户信息：', evaluateData.userInfo);
  
  // 这里可以调用API提交评价
  // 示例API调用：
  // post('/api/evaluate', {
  //   userId: evaluateData.userInfo.id,
  //   rating: evaluateData.rating,
  //   comment: evaluateData.comment,
  //   tags: evaluateData.tags
  // });
  
  Taro.showToast({
    title: '评价提交成功',
    icon: 'success',
    duration: 2000
  });
  
  evaluateModalVisible.value = false;
};

/**
 * 评价取消
 */
const handleEvaluateCancel = () => {
  evaluateModalVisible.value = false;
};

/**
 * 接受申请
 * @param {Object} applicant - 申请用户信息
 */
const handleAccept = (applicant) => {
  // if (applicant.status === 'accepted' || applicant.status === 'rejected') {
  //   return;
  // }

  Taro.showModal({
    title: "确认接受",
    content: `确定要接受 ${applicant.name} 的申请吗？`,
    success: (res) => {
      if (res.confirm) {
        // 更新申请状态
        // applicant.status = 'accepted';
        acceptApplicant(applicant);
        
        Taro.showToast({
          title: "已提交",
          icon: "success",
          duration: 2000,
        });

        // 这里可以调用API提交接受申请
        console.log("接受申请：", applicant.id);
      }
    },
  });
};

const acceptApplicant = (applicant) => {
  const type = Taro.getCurrentInstance().router.params.type;
  const urlMaps = {
    0: '/pages/post/my-publish',
    1: '/task/confirmExecution',
    2: '/pages/post/my-publish',
  }

  post(urlMaps[type], {
    memberId: applicant.id,
  }).then(res => {
    console.log("接受申请：", res);
  })
}

/**
 * 拒绝申请
 * @param {Object} applicant - 申请用户信息
 */
const handleReject = (applicant) => {
  if (applicant.status === 'accepted' || applicant.status === 'rejected') {
    return;
  }

  Taro.showModal({
    title: "确认拒绝",
    content: `确定要拒绝 ${applicant.name} 的申请吗？`,
    success: (res) => {
      if (res.confirm) {
        // 更新申请状态
        applicant.status = 'rejected';
        
        Taro.showToast({
          title: "已提交",
          icon: "success",
          duration: 2000,
        });

        // 这里可以调用API提交拒绝申请
        console.log("拒绝申请：", applicant.id);
      }
    },
  });
};

/**
 * 跳转到用户详情页
 * @param {Object} applicant - 申请用户信息
 */
function goToUserDetail(applicant) {
  // if (!applicant.id) return;
  // Taro.navigateTo({
  //   url: `/pages/mine/other?id=${applicant.id}`
  // });
}

// 页面加载时获取数据
onMounted(() => {
  // 从页面参数获取任务ID
  const pages = Taro.getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const { taskId } = currentPage.options;
  
  if (taskId) {
    // 根据任务ID加载对应的申请用户数据
    console.log("加载任务ID：", taskId);
    // 这里可以调用API获取申请用户列表
  }
});
</script> 